<template>
  <a-row class="login_box" v-title data-title="后羿零碳-登录">
    <a-col :span="24" class="left_row">
      <div class="register_from_container">
        <div class="login_header">
          <img src="@/assets/img/dc3.png" alt="" />
          <h2>ESG-企业版-注册</h2>
        </div>
        <div class="register_from_box">
          <div class=""></div>

          <a-steps class="steps_box" size="small">
            <a-step status="finish" title="账号信息设置">
              <a-icon slot="icon" type="user" />
            </a-step>
            <a-step status="finish" title="公司资质信息">
              <a-icon slot="icon" type="solution" />
            </a-step>
            <a-step status="process" title="等待审核">
              <a-icon slot="icon" type="loading" />
            </a-step>
          </a-steps>
          <a-form-model
            id="components-form-demo-normal-login"
            :model="model"
            ref="form"
            class="register-form"
            @keyup.enter.native="handleSubmit"
            :rules="validatorRules"
          >
            <a-form-model-item required prop="industryCode">
              <a-input
                v-model="model.industryCode"
                size="large"
                placeholder="请输入企业编码"
              >
                <a-icon
                  slot="prefix"
                  type="user"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
              <a-tooltip placement="top">
                <template slot="title">
                  <span style="font-size: 12px"
                    >企业编码是企业在后羿零碳的唯一标识，一企业一码永久保存。因为手机号因企业人员工作流动会很可能发生变更或调整，企业编码对比手机号具备更好的永久保存性。
                    <br />1、后羿零碳登录、找回密码均需要填写企业编码，建议设置企业编码尽量简洁，便于记忆，方便填写
                    <br />
                    2、
                    企业编码在后羿零碳具备唯一性，不能与其他企业编码重复，系统会自动校验唯一性</span
                  >
                </template>
                <span class="code_">企业编码是什么</span>
              </a-tooltip>
            </a-form-model-item>
            <a-form-model-item required prop="userName">
              <a-input
                v-model="model.userName"
                size="large"
                type="text"
                autocomplete="false"
                placeholder="请输入用户名"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
            </a-form-model-item>
            <a-form-model-item required prop="phone">
              <a-input
                v-model="model.phone"
                size="large"
                type="phone"
                autocomplete="false"
                placeholder="请输入手机号"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
            </a-form-model-item>
            <a-row :gutter="0">
              <a-col :span="17">
                <a-form-model-item required prop="verification">
                  <a-input
                    v-model="model.verification"
                    size="large"
                    type="text"
                    placeholder="请输入验证码"
                  >
                    <a-icon
                      slot="prefix"
                      type="smile"
                      :style="{ color: 'rgba(0,0,0,.25)' }"
                    />
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col
                :offset="1"
                :span="6"
                style="text-align: right"
                class="code"
                :class="[sendMsgDisabled ? 'code_click' : 'code_normal']"
                @click="getCode()"
              >
                <div v-if="!sendMsgDisabled">获取验证码</div>
                <div v-else>{{ time + "秒后获取" }}</div>
              </a-col>
            </a-row>
            <a-form-model-item prop="password">
              <a-input
                v-model="model.password"
                size="large"
                type="password"
                autocomplete="false"
                placeholder="登录密码"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
            </a-form-model-item>
            <a-form-model-item  prop="confirmpassword">
              <a-input
                v-model="model.confirmpassword"
                size="large"
                type="password"
                autocomplete="false"
                placeholder="重复登录密码"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  :style="{ color: 'rgba(0,0,0,.25)' }"
                />
              </a-input>
            </a-form-model-item>
            <a-form-model-item>
              <a-checkbox @change="handleRememberMeChange" default-checked
                >我已阅读并同意 <a href=""> 《用户协议》 </a>及<a href="">
                  《后羿零碳隐私声明》</a
                ></a-checkbox
              >

              <!-- <div @click="handleChangeCheckCode">刷新验证码</div> -->
              <a-button
                type="primary"
                @click.stop.prevent="handleSubmit"
                class="login-form-button"
              >
                下一步
              </a-button>

              <a
                @click="
                  () => {
                    $router.push('/login');
                  }
                "
              >
                返回登录
              </a>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </a-col>
  </a-row>
</template>

<script>
import { getAction, postAction } from "@/api/manage";
import { timeFix } from "@/utils/util";
import { duplicateCheck } from "@/api/api";
import Vue from "vue";
import { mapActions } from "vuex";
export default {
  name: "Login",
  data() {
    return {
      requestCodeSuccess: false,
      randCodeImage: "",
      currdatetime: "",
      rememberMe: false,
      time: 60, // 发送验证码倒计时
      sendMsgDisabled: false,
      model: {
          verification:111111,
          phone:13333141732
      },

      validatorRules: {
        industryCode: [{ required: true, message: "请输入企业编码!" }],
        userName: [{ required: true, message: "请输入用户账号!" }],
        phone: [
            { required: true, message: "请输入手机号!" },
            { validator: this.validatePhone },
        ],
        password: [
            // {
            //   required: true,
            //   pattern:
            //     /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            //   message: "密码由8位数字、大小写字母和特殊符号组成!",
            // },
            // { validator: this.validateToNextPassword, trigger: "change" },
        ],
        confirmpassword: [
            // { required: true, message: "请重新输入登录密码!" },
            // { validator: this.compareToFirstPassword },
        ],
        verification: [
          {
            required: true,
            message: "请输入验证码!",
          },
        ],
      },
    };
  },

  mounted() {},
  created() {
    this.handleChangeCheckCode();
  },
  methods: {
    getCode() {
      this.validateFields(["phone"], (err) => {
        if (!err) {
          const that = this;
          that.sendMsgDisabled = true;
          const interval = window.setInterval(function () {
            if (that.time-- <= 0) {
              that.time = 60;
              that.sendMsgDisabled = false;
              window.clearInterval(interval);
            }
          }, 1000);
        }
      });
    },

    validateUsername(rule, value, callback) {
      var params = {
        tableName: "sys_user",
        fieldName: "userName",
        fieldVal: value,
        dataId: this.userId,
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback();
        } else {
          callback("用户名已存在!");
        }
      });
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          callback();
          //   var params = {
          //     tableName: "sys_user",
          //     fieldName: "phone",
          //     fieldVal: value,
          //     dataId: this.userId,
          //   };
          //   duplicateCheck(params).then((res) => {
          //     if (res.success) {
          //       callback();
          //     } else {
          //       callback("手机号已存在!");
          //     }
          //   });
        } else {
          callback("请输入正确格式的手机号码!");
        }
      }
    },
    validateToNextPassword(rule, value, callback) {
      const confirmpassword = this.model.confirmpassword;
      if (value && confirmpassword && value !== confirmpassword) {
        callback("两次输入的密码不一样！");
      }
      if (value && this.confirmDirty) {
        this.$refs.form.validateField(["confirmpassword"]);
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.model.password) {
        callback("两次输入的密码不一样！");
      } else {
        callback();
      }
    },
    ...mapActions(["Login"]),
    // 登录事件
    handleSubmit(e) {
      //   this.handleLogin();
      this.$refs["form"].validate((success) => {
        if (success) {
          let register = this.model;
          //   console.log(register);
          postAction("/sys/regist/account", register).then((res) => {
            //   console.log(res);
            if (!res.success) {
              this.registerFailed(res.message);
            } else {
              this.$router.push({
                name: "registerResult",
                params: { ...values },
              });
            }
          });
        }
      });
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked;
    },
    handleLogin(rememberMe) {
      this.validateFields(["username", "password", "inputCode"], (err) => {
        if (!err) {
  
          //   console.log("登录参数", loginParams);
          this.Login(loginParams)
            .then((loginResult) => {
              this.$refs.loginSelect.show(loginResult.result);
              //   console.log("success", loginResult.result);
            })
            .catch((err) => {
              if (err && err.code === 412) {
                //   登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
                this.handleChangeCheckCode();
                //   console.log("fail", err);
              }
              this.requestFailed(err);
            });
        }
      });
    },
    // 登录失败
    requestFailed(err) {
      let description =
        ((err.response || {}).data || {}).message ||
        err.message ||
        "请求出现错误，请稍后再试";
      //   console.log(this.$notification);

      this.$notification["error"]({
        message: "登录失败",
        description: description,
        duration: 4,
      });
    },
    // 刷新验证码
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime();
      getAction(`/sys/randomImage/${this.currdatetime}`)
        .then((res) => {
          if (res.success) {
            this.randCodeImage = res.result;
            this.requestCodeSuccess = true;
          } else {
            this.$message.error(res.message);
            this.requestCodeSuccess = false;
          }
        })
        .catch(() => {
          this.requestCodeSuccess = false;
        });
    },
    loginSelectOk() {
      this.loginSuccess();
    },
    //登录成功
    loginSuccess() {
      // 如果没有部门的话 直接登录成功
      this.$router.push({ path: "/" }).catch(() => {
        //   console.log("登录跳转首页出错,这个错误从哪里来的");
      });
      this.$notification.success({
        message: "欢迎",
        description: `${timeFix()}，欢迎回来`,
      });
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = [];
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs["form"].validateField(item, (err) => {
            if (!err) {
              resolve();
            } else {
              reject(err);
            }
          });
        });
        promiseArray.push(p);
      }
      Promise.all(promiseArray)
        .then(() => {
          callback();
        })
        .catch((err) => {
          callback(err);
        });
    },
  },
};
</script>

<style lang="scss" >
#components-form-demo-normal-login .login-form {
  //   max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  height: 38px !important;
  font-size: 16px !important;
  width: 100%;
  background: #0176d3 !important;
  color: #fff !important;
  box-shadow: 2px 2px 8px #ccc;
}
.login_box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 100vh;
  width: 100%;
  .ant-form-explain {
    text-align: left !important;
    width: 100%;
    height: 100%;
  }
  .left_row {
    height: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background: #f4f6f9;

    .register_from_container {
      width: 100%;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .login_header {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;

        img {
          width: 60px;
          height: 60px;
        }
        h2 {
          font-weight: 600;
          font-size: 32px;
          padding-top: 6px;
          margin-left: 10px;
        }
      }
      .register_from_box {
        max-width: 900px;
        min-width: 600px;
        background: #fff;
      }
      .register_from_box {
        // width: 420px;
        background: #fff;
        padding: 60px 160px;
        border-radius: 5px;
        box-shadow: 2px 2px 7px rgb(212, 212, 212);
        border: 1px solid #f1f0f0;
        .code {
          height: 40px;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 5px;
          &:hover {
            opacity: 0.8;
            transition: 0.2s;
          }
        }
        .code_click {
          background: #ccc;
          color: #999;
          cursor: not-allowed;
        }
        .code_normal {
          background: #e6f0fd;
          color: #0c67ee;
        }
        .steps_box {
          margin-bottom: 30px;
        }
        .register-form {
          padding: 0 80px;
          .code_ {
            position: absolute;
            right: -90px;
            top: -3px;
            cursor: pointer;
            color: #0c67ee;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>